package com.kun.myproject;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.kun.ble.BleInit;
import com.kun.service.BluetoothLeService;
import com.kun.utils.CommonUtil;
import com.kun.utils.ToastUtil;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity2 extends AppCompatActivity implements MainView {

    @Bind(R.id.id_connect)
     Button connect;
    @Bind(R.id.id_send)
     Button send;
    @Bind(R.id.id_tv)
     TextView tv;
    @Bind(R.id.id_opcode)
     EditText ed_opcode;
    @Bind(R.id.id_opcode_data)
     EditText ed_opcode_data;

    private BluetoothLeService mBluetoothLeService;
    private boolean isConnect = false;
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    private Context ct;
    private ProgressDialog pd;
    private StringBuffer dataGet;
    private MainPresent mainPresent;
    private String send_data;
    private int opcode_num;

    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    tv.setText(dataGet.append("send:"+send_data+"\n"));
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                isConnect = true;
                connect.setText(R.string.connected);
                pd.dismiss();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                isConnect = false;
                connect.setText(R.string.connect_again);
                ToastUtil.toastShort(ct,R.string.disconnected);
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                //蓝牙接收到的数据都在这里
                String data = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
                mainPresent.analysis(data,Integer.parseInt(ed_opcode.getText().toString()));
            } else if (BluetoothLeService.ACTION_DATA_ERROR_CODE.equals(action)){
                mainPresent.write2ble(ed_opcode_data.getText().toString().trim(),opcode_num,mBluetoothLeService);
                SendData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)+"\n");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection,BIND_AUTO_CREATE);

        Bleinit();
        DataInit();
    }
    private void DataInit(){
        ed_opcode.setText("4");
        dataGet = new StringBuffer();
        ct = this;
        mainPresent = new MainPresent(this);
        mHandler = new Handler();
        if(!mBluetoothAdapter.isEnabled()){
            CommonUtil.showInfoDialog(this, getString(R.string.open_bluetooth), null, getString(R.string.sure), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mBluetoothAdapter.enable();
                }
            });
        }

    }
    @OnClick({R.id.id_send,R.id.id_connect})
    void onClick(View view) {
        switch (view.getId()){
            case R.id.id_send:
                if (isConnect){
                    opcode_num = Integer.parseInt(ed_opcode.getText().toString());
                    if (opcode_num>6||opcode_num<0) {
                        ToastUtil.toastShort(ct,"请输入0-6数字");
                        return;
                    }
//                    send2Ble(num);
                    mainPresent.write2ble(ed_opcode_data.getText().toString().trim(),opcode_num,mBluetoothLeService);
                }else {
                    ToastUtil.toastShort(this,R.string.please_connect);
                }
                break;
            case R.id.id_connect:
                if (isConnect) return;
                pd  = ProgressDialog.show(this,"正在连接蓝牙","请稍后....");
                scanLeDevice(true);
                break;
        }
    }

    private void Bleinit(){
        final BluetoothManager bluetoothManager =
                (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        if(!new BleInit().BleInit(this,mBluetoothAdapter)){
            ToastUtil.toastShort(this,R.string.ble_not_supported);
            return;
        }
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);//绑定服务
    }

    //搜索蓝牙
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // 扫描五秒钟
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(!isConnect) {
                        connect.setText(R.string.connect_again);
                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
                        pd.dismiss();
                    }
                }
            }, 5000);
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }
    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    String mDeviceAddress = device.getAddress();
                    if (device.getName() == null) return;
                    if (device.getName().equals("nfctest")&&mDeviceAddress!=null){
//                        若扫描到蓝牙硬件，停止扫描并连接
                        scanLeDevice(false);
                        if (!mBluetoothLeService.initialize()) {
                            ToastUtil.toastShort(ct,"Unable to initialize Bluetooth");
                            return;
                        }
                        ToastUtil.toastShort(ct,"正在连接nfctest");
                        mBluetoothLeService.connect(mDeviceAddress);
                    }
                }
            };

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mBluetoothLeService.close();
        unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_ERROR_CODE);
        return intentFilter;
    }

    @Override
    public void DataChange(String data, int opcode) {
        tv.setText(dataGet.append("opcode = " + opcode + ": "+data+"\n"));
    }

    @Override
    public void SendData(String send) {
        send_data = send;
        myHandler.sendEmptyMessage(1);
    }
}
